﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.MyLog;
using B.S.BasicData.Api.Read.DTOs;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.MyLog
{
    /// <summary>
    /// 查询日志分页列表的处理类
    /// </summary>
    public class SearchLogHandler : IRequestHandler<SearchLogCommand, ApiPaging<LogDTO>>
    {
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logRepo">日志仓储</param>
        public SearchLogHandler(IBaseRepository<LogModel> logRepo,IMapper mapper)
        {
            this.logRepo = logRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询日志分页列表的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<LogDTO>> Handle(SearchLogCommand request, CancellationToken cancellationToken)
        {
            //实例化响应包装类
            ApiPaging<LogDTO> res = new ApiPaging<LogDTO>();

            //查询表达式
            var logs = logRepo.GetAll().Where(x=>x.IsDeleted==false);

            //判断条件,如果请求参数(命令)里的日志内容不为空,就在查询表达式中加入日志内容条件
            if (!string.IsNullOrEmpty(request.LogDes)) {
                logs = logs.Where(x=>x.LogDes.Contains(request.LogDes));
            }

            //判断条件:创建人
            if (!string.IsNullOrEmpty(request.Creator))
            {
                logs = logs.Where(x => x.Creator.Contains(request.Creator));
            }
            //判断条件:创建时间
            if (request.CreateTime != null) {

                logs = logs.Where(x=>x.CreateTime.Value.Date== request.CreateTime.Value.Date);
            }


            //linq组合查询 


           res.TotalCount = logs.Count();//总条数

            List<LogModel> list = logs.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            res.PageDatas = mapper.Map<List<LogDTO>>(list);
            res.Msg = "查询日志分页列表成功!";
            res.Code = ApiEnum.Success;
            return res;


        }
    }
}
